const axios = require('axios')
const inquirer = require('inquirer')
const { promisify } = require('util')
const spinnerWrapper = require('./utils/spinnerWrapper.js')
const MetalSmith = require('metalsmith') // 遍历文件夹
let { render } = require('consolidate').ejs
let downLoadGit = require('download-git-repo')
let ncp = require('ncp')

downLoadGit = promisify(downLoadGit)
ncp = promisify(ncp)
render = promisify(render) // 包装渲染方法

const fetchRepoList = async () => {
  const response = await axios.get('https://gitee.com/api/v5/orgs/zero-cli-template/repos?access_token=d23000008beb5980238bd6485819213c&type=all&page=1&per_page=20')
  let names = response.data.map((v) => v.namespace.name)
  return names
}

const fetchTagList = async (repo) => {
  const response = await axios.get('https://gitee.com/api/v5/repos/zero-cli-template/zero-cli-react-template/releases?access_token=d23000008beb5980238bd6485819213c&page=1&per_page=20')

  return response.data.map((v) => v.tag_name)
}

module.exports = async (projectName) => {

  //请求repo list
  let repos = await spinnerWrapper(fetchRepoList, 'fetching repo list...')()
  //选择repo template
  let { repo } = await inquirer.prompt({
    name: 'repo',
    type: 'list',
    message: 'please choice repo template to create project',
    choices: repos
  })

  //请求template tag
  let tags = await spinnerWrapper(fetchTagList, 'fetching repo list...')(repo)
  //选择template tag
  let { tag } = await inquirer.prompt({
    name: 'tag',
    type: 'list',
    message: 'please choice repo releases tag to create project',
    choices: tags
  })


  //download
  const downloadDirectory = `${process.env[process.platform === 'darwin' ? 'HOME' : 'USERPROFILE']}/.template`
  
  const download = async (repo, tag) => {
    let api = `XXX/${repo}`
    if(tag) {
      api += `#${tag}`
    }
    const dest = `${downloadDirectory}/${repo}`
    await downLoadGit(api, dest)
    return dest
  }

  const target = await wrapFetchAddLoding(download, 'download template...')(repo, tag)

  //拷贝
  await ncp(target, path.join(path.resolve(), projectName))
  // console.log(`${process.env[process.platform === 'darwin' ? 'HOME' : 'USERPROFILE']}/.template`)


  if(!fs.existsSync(path.join(target, 'ask.js'))) {
    await ncp(target, path.join(path.resolve(), projectName))
  }
}